import { getUserRoutes, getUserInfo as getUserInfoApi } from '@/api/user'

const getDefaultState = () => {
  return {}
}
const state = getDefaultState()

const mutations = {}

const actions = {
  //更新菜单和路由
  login(context) {
    return new Promise((resolve, reject) => {
      // 移除 async
      const getUserInfoApiPromise = getUserInfoApi()
      const getUserRoutesPromise = getUserRoutes()
      Promise.all([getUserInfoApiPromise, getUserRoutesPromise])
        .then(([res1, res2]) => {
          if (res1.code === 20000 && res2.code === 20000) {
            context.commit('base/SET_USER_INFO', res1.data, { root: true })
            let menus = []
            let permissions = []
            res2.data.forEach(item => {
              if (item.type === 1 || item.type === 2 || item.type === 3) {
                menus.push(item)
              }
              if (item.permission) {
                permissions.push(item.permission)
              }
            })
            context.commit('base/SET_MENUS', menus, { root: true })
            context.commit('base/SET_ROUTER', menus, { root: true })
            context.commit('base/SET_PERMISSIONS', permissions, { root: true })
            resolve()
          } else {
            reject(new Error('Invalid response codes'))
          }
        })
        .catch(reject)
    })
  }
}

export default {
  namespaced: true, //命名空间
  state,
  mutations,
  actions
}
